package com.kmu.kmucampus.Fragment;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.kmu.kmucampus.R;
import com.kmu.kmucampus.activity.MainActivity;
import com.kmu.kmucampus.adapter.treeViewAdapter.SimpleTreeAdapter;
import com.kmu.kmucampus.adapter.treeViewAdapter.TreeListViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mytest.ssw.www.api.ActionCallbackListener;
import mytest.ssw.www.api.SqliteTools;
import mytest.ssw.www.core.DeptNodeCore;
import mytest.ssw.www.core.DeptNodeCoreImpl;
import mytest.ssw.www.mylibrary.Contents;
import mytest.ssw.www.mylibrary.DeptNode;
import mytest.ssw.www.mylibrary.getTheContent;

public class NoticeFragment extends Fragment {

    DeptNodeCore deptnodecore;
    private List<DeptNode> mDatas;
    private ListView mTree;
    private TreeListViewAdapter mAdapter;
    private float upPointX = 0;
    private int screenWidth;
    SQLiteDatabase db;
    private Button button22;
    private Button change_send;
    private String TAG = NoticeFragment.class.getName();
    List<getTheContent> contentList;
    ListView listView;
    private Context mContext;
    SqliteTools deptAllPoints;
    final String[] dept = new String[1];
    final ArrayList<String> deptAll = new ArrayList<String>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentnotice, container, false);
        listView = (ListView) view.findViewById(R.id.show);
        mContext = getContext();
        updateList();
        initDatas();
        final String tb_name="TB_STU";
        final SqliteTools sqlTool = new SqliteTools(getActivity().getFilesDir().toString());
        mTree = (ListView) view.findViewById(R.id.dept_tree);
        screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        mTree.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    upPointX = event.getX();
                    Log.i("qqqwWW", String.valueOf(upPointX));
                }
                return false;
            }
        });
        try {
            mAdapter = new SimpleTreeAdapter<DeptNode>(mTree, getContext(), mDatas, 1);
            mAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                @Override
                public void onClick(DeptNode node, int position) {
                    if (upPointX < screenWidth * 2 / 3) {
                        mAdapter.expandOrCollapse(position);
                    } else {
                        mAdapter.selectFlagUpdate(position);
                        deptAll.clear();
                        for(int i=0; i<mDatas.size();i++){
                            if(mDatas.get(i).getSelectFlag()==2&&mDatas.get(i).getNum().length()>16){
                                deptAll.add(mDatas.get(i).getNum());
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


        mTree.setAdapter(mAdapter);
        Log.i(TAG, "--------onCreateView");
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.d("Addr-create11", "save is not null");
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button22 = (Button) getActivity().findViewById(R.id.button_send);
        change_send = (Button) getActivity().findViewById(R.id.change_send);
        final TextView tip1 = (TextView) getActivity().findViewById(R.id.tip1);
        final EditText notice1 = (EditText) getActivity().findViewById(R.id.notice1);
        final TextView notice3 = (TextView) getActivity().findViewById(R.id.notice3);
        final Button button_send = (Button) getActivity().findViewById(R.id.button_send);
        final Button recivers_send = (Button) getActivity().findViewById(R.id.recivers_send);
        final ListView dept_tree = (ListView) getActivity().findViewById(R.id.dept_tree);
        recivers_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                change_send.setVisibility(View.GONE);
                tip1.setVisibility(View.GONE);
                notice1.setVisibility(View.GONE);
                notice3.setVisibility(View.GONE);
                recivers_send.setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
                button22.setVisibility(View.VISIBLE);
                dept_tree.setVisibility(View.VISIBLE);

//                    addrbook_List1.setVisibility(View.VISIBLE);
            }
        });
        button22.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sendNum="";
                final SqliteTools sqlTool = new SqliteTools(getActivity().getFilesDir().toString());
                List<Contents> contentss=new ArrayList<Contents>();
                for(int i=0;i<deptAll.size();i++){
                    //deptAll.get(0);
                    Log.i("num00099", deptAll.get(i));
                    contentss.addAll(sqlTool.getTeacherInfoFrDB("TB_STU", deptAll.get(i)));
                }
                Log.i("contentss.size", ""+contentss.size());

                for(int j=0 ; j< contentss.size();j++) {
                    if(j==0)  sendNum=contentss.get(j).getNum().toString();
                    else   sendNum = sendNum+","+contentss.get(j).getNum().toString();
                    Log.i("childnumkk", sendNum);
                }
                change_send.setVisibility(View.VISIBLE);
                listView.setVisibility(View.VISIBLE);
                button22.setVisibility(View.GONE);
                dept_tree.setVisibility(View.GONE);
                Toast.makeText(getActivity(), "发送成功", Toast.LENGTH_SHORT).show();
                final String account = getActivity().getIntent().getExtras().getString("account");
                EditText content = (EditText) getActivity().findViewById(R.id.notice1);
                String contentP;
                contentP = content.getText().toString();
                Log.i(TAG, "--------getcontent");
                //下面修改为获取发送人树
                TextView receiverNumbP = (TextView) getActivity().findViewById(R.id.notice3);
                String receiverNumbPP = sendNum;
//              Toast.makeText(getActivity(), "发送成功", Toast.LENGTH_SHORT).show();
                updateList();
                Log.i(TAG, "--------getpersonNum");
                ((MainActivity) getActivity()).appAction.sendpost(contentP, account, receiverNumbPP, new ActionCallbackListener<Void>() {
                    @Override
                    public void onSuccess(Void data) {
                        Toast.makeText(getActivity(), "发送成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(String errorEvent, String message) {
                        Toast.makeText(getActivity(), errorEvent, Toast.LENGTH_SHORT).show();
                    }
                });
                updateList();
            }
        });
        change_send.setOnClickListener(new View.OnClickListener() {
            boolean visibility_Flag = true;

            public void onClick(View v) {
                if (visibility_Flag) {
                    button22.setVisibility(View.VISIBLE);
                    tip1.setVisibility(View.VISIBLE);
                    notice1.setVisibility(View.VISIBLE);
                    notice3.setVisibility(View.GONE);
                    listView.setVisibility(View.GONE);
                    recivers_send.setVisibility(View.VISIBLE);
                    button_send.setVisibility(View.GONE);
                    dept_tree.setVisibility(View.GONE);
                    change_send.setText("收起");
                    visibility_Flag = false;

                } else {
                    button22.setVisibility(View.GONE);
                    tip1.setVisibility(View.GONE);
                    notice1.setVisibility(View.GONE);
                    notice3.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);
                    button_send.setVisibility(View.GONE);
                    recivers_send.setVisibility(View.GONE);
                    updateList();
                    change_send.setText("发送通知");
                    visibility_Flag = true;
                }
            }
        });
        Log.i(TAG, "--------onActivityCreated");
    }

    public void serverToDB() {
        final String account = getActivity().getIntent().getExtras().getString("account");
        ((MainActivity) getActivity()).appAction.GetTheContentList(account, new ActionCallbackListener<List<getTheContent>>() {
            @Override
            public void onSuccess(List<getTheContent> data) {
                loadDB(data);
            }

            @Override
            public void onFailure(String errorEvent, String element) {
                Toast.makeText(getActivity(), errorEvent, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void updateList() {
        serverToDB();
        inflateList(initDB());
    }

    public void initDialog(final List<getTheContent> data) {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                alertDialog.setTitle(data.get(position).getSendPerson());
                alertDialog.setMessage("内容:" + data.get(position).getNoticeContent() + "\n"
                        + "发送人:" + data.get(position).getSendPersonNum());
                alertDialog.setPositiveButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                Log.d("setOnItemClickListener", Long.toString(id));
                if (data.get(position).getId() != null) {
                    final String aaa = data.get(position).getId();
                    alertDialog.setNegativeButton("删除", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //删除事件
                                    db = SQLiteDatabase.openOrCreateDatabase(getActivity().getFilesDir().toString() + "/mm.db3", null);
                                    final String account = getActivity().getIntent().getExtras().getString("account");
                                    String sql = "delete from " + "table_" + account + " where id=?";
                                    db.execSQL(sql, new String[]{aaa});
                                    updateList();
                                    Log.i("there.aaa=", aaa);
                                }
                            }
                    );
                }
                alertDialog.show();
            }
        });
    }

    public void loadDB(List<getTheContent> data) {
        int i;
        for (i = 0; i < data.size(); i++) {
            String dateN;
            long a;
            final String account = getActivity().getIntent().getExtras().getString("account");
            a = data.get(i).getSendTime();
            Date getDate = new Date(a);
            SimpleDateFormat asd = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
            dateN = asd.format(getDate);
            ContentValues insertInfo = new ContentValues();
            insertInfo.put("id", data.get(i).getId());
            insertInfo.put("noticeContent", data.get(i).getNoticeContent());
            insertInfo.put("noticeType", data.get(i).getNoticeType());
            insertInfo.put("sendPerson", data.get(i).getSendPerson());
            insertInfo.put("sendPersonNum", data.get(i).getSendPersonNum());
            insertInfo.put("sendTime", dateN);
            db.insert("table_" + account, null, insertInfo);
        }
    }

    public Cursor initDB() {
        Cursor cursor;
        db = SQLiteDatabase.openOrCreateDatabase(getActivity().getFilesDir().toString() + "/mm.db3", null);
        try {
            final String account = getActivity().getIntent().getExtras().getString("account");
            String sql = "select * from " + "table_" + account + " order by sendTime DESC ";
            cursor = db.rawQuery(sql, null);
            inflateList(cursor);
        } catch (SQLiteException se) {
            final String account = getActivity().getIntent().getExtras().getString("account");
            String sql = "create table " + "table_" + account + " (_id integer primary key autoincrement, id varchar(30),  noticeContent varchar(255), noticeType varchar(100),  sendPerson varchar(30),  sendPersonNum varchar(30),  sendTime varchar(100) )";
            db.execSQL(sql);
            String sqli = "select * from " + "table_" + account + " order by sendTime DESC ";
            cursor = db.rawQuery(sqli, null);
        }
        return cursor;
    }

    //装载到list
    public List<getTheContent> getAllPoints(Cursor cursor) {
        db = SQLiteDatabase.openOrCreateDatabase(getActivity().getFilesDir().toString() + "/mm.db3", null);
        List<getTheContent> pointList = new ArrayList<getTheContent>();
        getTheContent point = null;
        cursor.moveToFirst();
        boolean b = true;
        while (b) {
            if (cursor.getCount() != 0) {
                point = new getTheContent();
                point.setId(cursor.getString(cursor.getColumnIndex("id")));
                point.setNoticeContent(cursor.getString(cursor.getColumnIndex("noticeContent")));
                point.setNoticeType(cursor.getString(cursor.getColumnIndex("noticeType")));
                point.setSendPerson(cursor.getString(cursor.getColumnIndex("sendPerson")));
                point.setSendPersonNum(cursor.getString(cursor.getColumnIndex("sendPersonNum")));
                point.setSendTime(cursor.getLong(cursor.getColumnIndex("sendTime")));
                pointList.add(point);
            }
            b = cursor.moveToNext();
        }
        return pointList;
    }

    //逐条添加适配器
    private void inflateList(Cursor cursor) {
        cursor.moveToFirst();
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(NoticeFragment.super.getActivity(), R.layout.line, cursor, new String[]{"noticeContent", "sendPerson", "sendTime"}, new int[]{R.id.my_content, R.id.send_person, R.id.send_time});
        //显示数据
        initDialog(getAllPoints(cursor));
        listView.setAdapter(adapter);
    }


    //数据库导入方法
    private void initDatas() {
        deptnodecore = new DeptNodeCoreImpl(getActivity());
        mDatas = deptnodecore.getBylevel(1);
        StringBuffer MM = new StringBuffer();
        for (DeptNode d : mDatas) {
            MM.append("id=" + d.getId() + ",num=" + d.getNum() + ",name=" + d.getName() + ",level=" + d.getLevel() + ",leaf=" + d.isLeaf() + ",valid=" + d.isValid() + ",pNum=" + d.getpNum() + ",orderNum=" + d.getOrderNum() + ",fullName=" + d.getFullName() + ";  ");
        }
        Log.i("BM_01_02qq", MM.toString());

    }

    //关闭数据库
    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出程序时关闭SQLiteDatabase
        if (db != null && db.isOpen()) {
            db.close();
        }
    }
}